package com.jws.battleship;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class NetworkFactoryActivity extends Activity {

	public final static int idBlueToothDiscoveryRequest = 2;
	
	private NetworkInterface NI = null;
	
	private ArrayList<String> mBluetoothDevices = new ArrayList<String>();
	private ArrayList<BluetoothDevice> mFoundBluetoothDevices = new ArrayList<BluetoothDevice>();
	private ArrayAdapter<String> mBluetoothListAdapter;
	private UUID mUUID;
	private String mJoinCreate;
	private String mBluetoothServerSocketName = "bluetoothserver";
	private String mCreateServerSocket = "ServerSocket";
	private String mCreateClientSocket = "ClientSocket";
	private static Boolean isRegistered = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mUUID = UUID.fromString(getString(R.string.BluetoothUUID));
		
		Intent mIntent = getIntent();
		mJoinCreate = mIntent.getStringExtra(getString(R.string.NetworkFactoryNewNetwork));
		setContentView(R.layout.network_factory_bluetooth_devices);
		if(mJoinCreate != null)
		{
			setupBlueTooth();
		}
	}
	public void setupBlueTooth()
	{
		try {
			NI = NetworkInterface.getInstance();
		} catch (Exception e) {
			NI = new BluetoothNetwork();
			NetworkInterface.setInstance(NI);
		}
		BluetoothNetwork mBluetoothNetwork = (BluetoothNetwork) NI;
		
		if(mBluetoothNetwork.getAdapter() == null)
		{
			mBluetoothNetwork.setAdapter(BluetoothAdapter.getDefaultAdapter());
		}
		if(mBluetoothNetwork.getAdapter().getScanMode() == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
			bluetoothJoinCreate();
		else
		{
			Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
			startActivityForResult(intent, idBlueToothDiscoveryRequest);
		}
	}
	
	@Override
	public void unregisterReceiver(BroadcastReceiver receiver) {
		
		if(isRegistered)
		{
			isRegistered = false;
			super.unregisterReceiver(receiver);
		}
			
	}
	
	private BroadcastReceiver BluetoothdiscoveryResult = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			isRegistered = true;
			String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
			BluetoothDevice remoteDevice;
			remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			if (remoteDevice.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.PHONE_SMART)
			{
				mFoundBluetoothDevices.add(remoteDevice);
				mBluetoothDevices.add(remoteDeviceName);
				mBluetoothListAdapter.notifyDataSetChanged();
			}
			
		}
	};
	
	private OnItemClickListener bluetoothOpponentSelect = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int posistion, long arg3) 
		{
			BluetoothNetwork mBluetoothNetwork = (BluetoothNetwork) NI;
			mBluetoothNetwork.setDevice(mFoundBluetoothDevices.get(posistion));
			ListView deviceList = (ListView)findViewById(R.id.network_factory_bluetooth_device_list);
			TextView waitText = (TextView)findViewById(R.id.network_factory_wait);
			deviceList.setVisibility(View.GONE);
			waitText.setVisibility(View.VISIBLE);
			
			asynch task = new asynch();
			task.execute(mCreateClientSocket);			
		}
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == idBlueToothDiscoveryRequest)
		{
			if(resultCode > 0)
			{
				bluetoothJoinCreate();
			}
			else
			{
				finish();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void bluetoothJoinCreate()
	{
		if(mJoinCreate.equals(getString(R.string.NetworkFactoryJoinGame)))
		{
			BluetoothNetwork mBluetoothNetwork = (BluetoothNetwork) NI;
			registerReceiver(BluetoothdiscoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
			
			if (!mBluetoothNetwork.getAdapter().isDiscovering())
				mBluetoothNetwork.getAdapter().startDiscovery();
			
			mBluetoothListAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mBluetoothDevices);
			//setContentView(R.layout.network_factory_bluetooth_devices);

			ListView list = (ListView)findViewById(R.id.network_factory_bluetooth_device_list);
			list.setAdapter(mBluetoothListAdapter);
			list.setOnItemClickListener(bluetoothOpponentSelect);
		}
		else
		{
			setContentView(R.layout.network_factory_wait_screen);
			
			TextView text = (TextView)findViewById(R.id.network_factory_wait_text);
			Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.flashing);
			text.startAnimation(animation);
			
			asynch task = new asynch();
			task.execute(mCreateServerSocket);
		}
	}
	
	public void stopWaitingOnClick(View v)
	{
		unregisterReceiver(BluetoothdiscoveryResult);
		finish();
	}
	@Override
	protected void onDestroy() {

		unregisterReceiver(BluetoothdiscoveryResult);
		super.onDestroy();
	}
	
	private class asynch extends AsyncTask<String, Integer, Boolean>
	{

		@Override
		protected Boolean doInBackground(String... params) {
			
			if(params.length == 1)
			{
				BluetoothNetwork mBluetoothNetwork = (BluetoothNetwork) NI;
				if(params[0].equals(mCreateServerSocket))
				{
					
					String name = mBluetoothServerSocketName;
					try {
						final BluetoothServerSocket btserver =
						mBluetoothNetwork.getAdapter().listenUsingRfcommWithServiceRecord(name, mUUID);
						mBluetoothNetwork.setSocket(btserver.accept());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
				}
				else if(params[0].equals(mCreateClientSocket))
				{
					try
					{
						BluetoothDevice device = mBluetoothNetwork.getDevice();
						BluetoothSocket clientSocket = device.createRfcommSocketToServiceRecord(mUUID);
						mBluetoothNetwork.setSocket(clientSocket);
						clientSocket.connect();
					} 
					catch (IOException e) 
					{
						e.printStackTrace();
					}
				}
			}
			return null;
			
			
		}
		@Override
		protected void onPostExecute(Boolean result) {
			unregisterReceiver(BluetoothdiscoveryResult);
			Intent intent = new Intent(getApplicationContext(), BattleActivity.class);
			
			startActivity(intent);
			
			super.onPostExecute(result);
		}
		
	}
}
